#include "rtos_abstraction.h"
#include <string.h>

/* 配置选项 - 在编译时定义 USE_FREERTOS, USE_RTTHREAD 或 USE_PTHREAD */
#if !defined(USE_FREERTOS) && !defined(USE_RTTHREAD) && !defined(USE_PTHREAD)
#error "Please define USE_FREERTOS, USE_RTTHREAD or USE_PTHREAD"
#endif

#ifdef USE_FREERTOS
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "event_groups.h"
#include "timers.h"
#include "queue.h"
#elif defined(USE_RTTHREAD)
#include <rtthread.h>
#elif defined(USE_PTHREAD)
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <time.h>
#include <errno.h>
#endif

/* 内存管理 */
void* rtos_malloc(size_t size)
{
#ifdef USE_FREERTOS
    return pvPortMalloc(size);
#elif defined(USE_RTTHREAD)
    return rt_malloc(size);
#elif defined(USE_PTHREAD)
    return malloc(size);
#endif
}

void rtos_free(void *ptr)
{
#ifdef USE_FREERTOS
    vPortFree(ptr);
#elif defined(USE_RTTHREAD)
    rt_free(ptr);
#elif defined(USE_PTHREAD)
    free(ptr);
#endif
}

/* 系统信息 */
bool rtos_in_isr(void)
{
#ifdef USE_FREERTOS
    return xPortIsInsideInterrupt();
#elif defined(USE_RTTHREAD)
    return rt_interrupt_get_nest() > 0;
#elif defined(USE_PTHREAD)
    return false; // pthread没有ISR概念
#endif
}

uint32_t rtos_get_tick_count(void)
{
#ifdef USE_FREERTOS
    return xTaskGetTickCount();
#elif defined(USE_RTTHREAD)
    return rt_tick_get();
#elif defined(USE_PTHREAD)
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
#endif
}

uint32_t rtos_get_tick_frequency(void)
{
#ifdef USE_FREERTOS
    return configTICK_RATE_HZ;
#elif defined(USE_RTTHREAD)
    return RT_TICK_PER_SECOND;
#elif defined(USE_PTHREAD)
    return 1000; // pthread使用毫秒计时
#endif
}

/* 任务管理 */
rtos_task_t rtos_task_create(void (*task_func)(void *), 
                            const char *name,
                            uint32_t stack_size,
                            void *param,
                            uint32_t priority)
{
#ifdef USE_FREERTOS
    TaskHandle_t handle;
    BaseType_t ret = xTaskCreate(task_func, name, stack_size, param, 
                                priority, &handle);
    return (ret == pdPASS) ? (rtos_task_t)handle : NULL;
#elif defined(USE_RTTHREAD)
    rt_thread_t thread = rt_thread_create(name, task_func, param, 
                                        stack_size, priority, 20);
    if (thread != RT_NULL && rt_thread_startup(thread) == RT_EOK) {
        return (rtos_task_t)thread;
    }
    return NULL;
#elif defined(USE_PTHREAD)
    pthread_t thread;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, stack_size);
    
    struct sched_param sched;
    sched.sched_priority = priority;
    pthread_attr_setschedparam(&attr, &sched);
    
    int ret = pthread_create(&thread, &attr, (void*(*)(void*))task_func, param);
    pthread_attr_destroy(&attr);
    return (ret == 0) ? (rtos_task_t)(uintptr_t)thread : NULL;
#endif
}

void rtos_task_delete(rtos_task_t task)
{
#ifdef USE_FREERTOS
    vTaskDelete((TaskHandle_t)task);
#elif defined(USE_RTTHREAD)
    rt_thread_delete((rt_thread_t)task);
#elif defined(USE_PTHREAD)
    pthread_cancel((pthread_t)(uintptr_t)task);
    pthread_join((pthread_t)(uintptr_t)task, NULL);
#endif
}

void rtos_task_delay(uint32_t ms)
{
#ifdef USE_FREERTOS
    vTaskDelay(pdMS_TO_TICKS(ms));
#elif defined(USE_RTTHREAD)
    rt_thread_mdelay(ms);
#elif defined(USE_PTHREAD)
    usleep(ms * 1000);
#endif
}

void rtos_task_suspend(rtos_task_t task)
{
#ifdef USE_FREERTOS
    vTaskSuspend((TaskHandle_t)task);
#elif defined(USE_RTTHREAD)
    rt_thread_suspend((rt_thread_t)task);
#elif defined(USE_PTHREAD)
    // pthread没有直接的suspend功能
#endif
}

void rtos_task_resume(rtos_task_t task)
{
#ifdef USE_FREERTOS
    vTaskResume((TaskHandle_t)task);
#elif defined(USE_RTTHREAD)
    rt_thread_resume((rt_thread_t)task);
#elif defined(USE_PTHREAD)
    // pthread没有直接的resume功能
#endif
}

rtos_task_t rtos_task_self(void)
{
#ifdef USE_FREERTOS
    return (rtos_task_t)xTaskGetCurrentTaskHandle();
#elif defined(USE_RTTHREAD)
    return (rtos_task_t)rt_thread_self();
#elif defined(USE_PTHREAD)
    return (rtos_task_t)(uintptr_t)pthread_self();
#endif
}

/* 信号量 */
rtos_sem_t rtos_sem_create(uint32_t initial_count, uint32_t max_count)
{
#ifdef USE_FREERTOS
    return (rtos_sem_t)xSemaphoreCreateCounting(max_count, initial_count);
#elif defined(USE_RTTHREAD)
    rt_sem_t sem = rt_sem_create("sem", initial_count, RT_IPC_FLAG_FIFO);
    return (rtos_sem_t)sem;
#elif defined(USE_PTHREAD)
    sem_t *sem = (sem_t *)malloc(sizeof(sem_t));
    if (sem && sem_init(sem, 0, initial_count) == 0) {
        return (rtos_sem_t)sem;
    }
    free(sem);
    return NULL;
#endif
}

int rtos_sem_take(rtos_sem_t sem, uint32_t timeout_ms)
{
#ifdef USE_FREERTOS
    return (xSemaphoreTake((SemaphoreHandle_t)sem, 
                         timeout_ms == RTOS_WAIT_FOREVER ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms)) 
            == pdTRUE) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_RTTHREAD)
    rt_err_t result = rt_sem_take((rt_sem_t)sem, 
                                timeout_ms == RTOS_WAIT_FOREVER ? RT_WAITING_FOREVER : rt_tick_from_millisecond(timeout_ms));
    return (result == RT_EOK) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_PTHREAD)
    sem_t *psem = (sem_t *)sem;
    if (timeout_ms == RTOS_NO_WAIT) {
        return (sem_trywait(psem) == 0) ? RTOS_OK : RTOS_TIMEOUT;
    } else if (timeout_ms == RTOS_WAIT_FOREVER) {
        return (sem_wait(psem) == 0) ? RTOS_OK : RTOS_ERROR;
    } else {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        ts.tv_sec += timeout_ms / 1000;
        ts.tv_nsec += (timeout_ms % 1000) * 1000000;
        if (ts.tv_nsec >= 1000000000) {
            ts.tv_sec++;
            ts.tv_nsec -= 1000000000;
        }
        return (sem_timedwait(psem, &ts) == 0) ? RTOS_OK : RTOS_TIMEOUT;
    }
#endif
}

int rtos_sem_give(rtos_sem_t sem)
{
#ifdef USE_FREERTOS
    return (xSemaphoreGive((SemaphoreHandle_t)sem) == pdTRUE) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_RTTHREAD)
    return (rt_sem_release((rt_sem_t)sem) == RT_EOK) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_PTHREAD)
    return (sem_post((sem_t *)sem) == 0) ? RTOS_OK : RTOS_ERROR;
#endif
}

int rtos_sem_give_from_isr(rtos_sem_t sem)
{
#ifdef USE_FREERTOS
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    BaseType_t result = xSemaphoreGiveFromISR((SemaphoreHandle_t)sem, &xHigherPriorityTaskWoken);
    if (xHigherPriorityTaskWoken) {
        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
    }
    return (result == pdTRUE) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_RTTHREAD)
    if (rt_interrupt_get_nest() > 0) {
        return (rt_sem_release((rt_sem_t)sem) == RT_EOK) ? RTOS_OK : RTOS_ERROR;
    }
    return rtos_sem_give(sem);
#elif defined(USE_PTHREAD)
    return rtos_sem_give(sem); // pthread没有ISR概念
#endif
}

void rtos_sem_delete(rtos_sem_t sem)
{
#ifdef USE_FREERTOS
    vSemaphoreDelete((SemaphoreHandle_t)sem);
#elif defined(USE_RTTHREAD)
    rt_sem_delete((rt_sem_t)sem);
#elif defined(USE_PTHREAD)
    sem_destroy((sem_t *)sem);
    free(sem);
#endif
}

/* 互斥锁 */
rtos_mutex_t rtos_mutex_create(void)
{
#ifdef USE_FREERTOS
    return (rtos_mutex_t)xSemaphoreCreateMutex();
#elif defined(USE_RTTHREAD)
    rt_mutex_t mutex = rt_mutex_create("mutex", RT_IPC_FLAG_FIFO);
    return (rtos_mutex_t)mutex;
#elif defined(USE_PTHREAD)
    pthread_mutex_t *mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
    if (mutex && pthread_mutex_init(mutex, NULL) == 0) {
        return (rtos_mutex_t)mutex;
    }
    free(mutex);
    return NULL;
#endif
}

int rtos_mutex_lock(rtos_mutex_t mutex, uint32_t timeout_ms)
{
#ifdef USE_FREERTOS
    return (xSemaphoreTake((SemaphoreHandle_t)mutex, 
                         timeout_ms == RTOS_WAIT_FOREVER ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms)) 
            == pdTRUE) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_RTTHREAD)
    rt_err_t result = rt_mutex_take((rt_mutex_t)mutex, 
                                  timeout_ms == RTOS_WAIT_FOREVER ? RT_WAITING_FOREVER : rt_tick_from_millisecond(timeout_ms));
    return (result == RT_EOK) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_PTHREAD)
    pthread_mutex_t *pmutex = (pthread_mutex_t *)mutex;
    if (timeout_ms == RTOS_NO_WAIT) {
        return (pthread_mutex_trylock(pmutex) == 0) ? RTOS_OK : RTOS_TIMEOUT;
    } else if (timeout_ms == RTOS_WAIT_FOREVER) {
        return (pthread_mutex_lock(pmutex) == 0) ? RTOS_OK : RTOS_ERROR;
    } else {
        // pthread没有直接的带超时锁，模拟实现
        uint32_t start = rtos_get_tick_count();
        while (pthread_mutex_trylock(pmutex) != 0) {
            if (rtos_get_tick_count() - start >= timeout_ms) {
                return RTOS_TIMEOUT;
            }
            usleep(1000); // 1ms delay
        }
        return RTOS_OK;
    }
#endif
}

int rtos_mutex_unlock(rtos_mutex_t mutex)
{
#ifdef USE_FREERTOS
    return (xSemaphoreGive((SemaphoreHandle_t)mutex) == pdTRUE) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_RTTHREAD)
    return (rt_mutex_release((rt_mutex_t)mutex) == RT_EOK) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_PTHREAD)
    return (pthread_mutex_unlock((pthread_mutex_t *)mutex) == 0) ? RTOS_OK : RTOS_ERROR;
#endif
}

void rtos_mutex_delete(rtos_mutex_t mutex)
{
#ifdef USE_FREERTOS
    vSemaphoreDelete((SemaphoreHandle_t)mutex);
#elif defined(USE_RTTHREAD)
    rt_mutex_delete((rt_mutex_t)mutex);
#elif defined(USE_PTHREAD)
    pthread_mutex_destroy((pthread_mutex_t *)mutex);
    free(mutex);
#endif
}

/* 消息队列 */
typedef struct {
#ifdef USE_PTHREAD
    pthread_mutex_t lock;
    pthread_cond_t cond;
    uint8_t *buffer;
    uint32_t head;
    uint32_t tail;
    uint32_t item_size;
    uint32_t max_items;
    uint32_t count;
#endif
} rtos_queue_internal_t;

rtos_queue_t rtos_queue_create(uint32_t length, uint32_t item_size)
{
#ifdef USE_FREERTOS
    return (rtos_queue_t)xQueueCreate(length, item_size);
#elif defined(USE_RTTHREAD)
    rt_mq_t mq = rt_mq_create("mq", item_size, length, RT_IPC_FLAG_FIFO);
    return (rtos_queue_t)mq;
#elif defined(USE_PTHREAD)
    rtos_queue_internal_t *queue = (rtos_queue_internal_t *)malloc(sizeof(rtos_queue_internal_t));
    if (!queue) return NULL;
    
    queue->buffer = (uint8_t *)malloc(length * item_size);
    if (!queue->buffer) {
        free(queue);
        return NULL;
    }
    
    pthread_mutex_init(&queue->lock, NULL);
    pthread_cond_init(&queue->cond, NULL);
    queue->head = 0;
    queue->tail = 0;
    queue->item_size = item_size;
    queue->max_items = length;
    queue->count = 0;
    
    return (rtos_queue_t)queue;
#endif
}

int rtos_queue_send(rtos_queue_t queue, const void *item, uint32_t timeout_ms)
{
#ifdef USE_FREERTOS
    return (xQueueSend((QueueHandle_t)queue, item, 
                     timeout_ms == RTOS_WAIT_FOREVER ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms)) 
            == pdPASS) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_RTTHREAD)
    rt_err_t result = rt_mq_send((rt_mq_t)queue, item, 
                                ((struct rt_messagequeue *)queue)->msg_size);
    return (result == RT_EOK) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_PTHREAD)
    rtos_queue_internal_t *q = (rtos_queue_internal_t *)queue;
    struct timespec ts;
    int ret = RTOS_ERROR;
    
    pthread_mutex_lock(&q->lock);
    
    if (timeout_ms != RTOS_NO_WAIT) {
        if (timeout_ms != RTOS_WAIT_FOREVER) {
            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += timeout_ms / 1000;
            ts.tv_nsec += (timeout_ms % 1000) * 1000000;
            if (ts.tv_nsec >= 1000000000) {
                ts.tv_sec++;
                ts.tv_nsec -= 1000000000;
            }
        }
        
        while (q->count == q->max_items) {
            if (timeout_ms == RTOS_WAIT_FOREVER) {
                pthread_cond_wait(&q->cond, &q->lock);
            } else {
                if (pthread_cond_timedwait(&q->cond, &q->lock, &ts) == ETIMEDOUT) {
                    pthread_mutex_unlock(&q->lock);
                    return RTOS_TIMEOUT;
                }
            }
        }
    } else if (q->count == q->max_items) {
        pthread_mutex_unlock(&q->lock);
        return RTOS_TIMEOUT;
    }
    
    if (q->count < q->max_items) {
        memcpy(&q->buffer[q->head * q->item_size], item, q->item_size);
        q->head = (q->head + 1) % q->max_items;
        q->count++;
        ret = RTOS_OK;
        pthread_cond_signal(&q->cond);
    }
    
    pthread_mutex_unlock(&q->lock);
    return ret;
#endif
}

int rtos_queue_send_from_isr(rtos_queue_t queue, const void *item)
{
#ifdef USE_FREERTOS
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    BaseType_t result = xQueueSendFromISR((QueueHandle_t)queue, item, &xHigherPriorityTaskWoken);
    if (xHigherPriorityTaskWoken) {
        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
    }
    return (result == pdPASS) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_RTTHREAD)
    if (rt_interrupt_get_nest() > 0) {
        return (rt_mq_send((rt_mq_t)queue, item, 
                          ((struct rt_messagequeue *)queue)->msg_size) == RT_EOK) ? RTOS_OK : RTOS_ERROR;
    }
    return rtos_queue_send(queue, item, RTOS_NO_WAIT);
#elif defined(USE_PTHREAD)
    return rtos_queue_send(queue, item, RTOS_NO_WAIT); // pthread没有ISR概念
#endif
}

int rtos_queue_receive(rtos_queue_t queue, void *item, uint32_t timeout_ms)
{
#ifdef USE_FREERTOS
    return (xQueueReceive((QueueHandle_t)queue, item, 
                         timeout_ms == RTOS_WAIT_FOREVER ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms)) 
            == pdPASS) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_RTTHREAD)
    rt_err_t result = rt_mq_recv((rt_mq_t)queue, item, 
                               ((struct rt_messagequeue *)queue)->msg_size, 
                               timeout_ms == RTOS_WAIT_FOREVER ? RT_WAITING_FOREVER : rt_tick_from_millisecond(timeout_ms));
    return (result == RT_EOK) ? RTOS_OK : RTOS_TIMEOUT;
#elif defined(USE_PTHREAD)
    rtos_queue_internal_t *q = (rtos_queue_internal_t *)queue;
    struct timespec ts;
    int ret = RTOS_ERROR;
    
    pthread_mutex_lock(&q->lock);
    
    if (timeout_ms != RTOS_NO_WAIT) {
        if (timeout_ms != RTOS_WAIT_FOREVER) {
            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += timeout_ms / 1000;
            ts.tv_nsec += (timeout_ms % 1000) * 1000000;
            if (ts.tv_nsec >= 1000000000) {
                ts.tv_sec++;
                ts.tv_nsec -= 1000000000;
            }
        }
        
        while (q->count == 0) {
            if (timeout_ms == RTOS_WAIT_FOREVER) {
                pthread_cond_wait(&q->cond, &q->lock);
            } else {
                if (pthread_cond_timedwait(&q->cond, &q->lock, &ts) == ETIMEDOUT) {
                    pthread_mutex_unlock(&q->lock);
                    return RTOS_TIMEOUT;
                }
            }
        }
    } else if (q->count == 0) {
        pthread_mutex_unlock(&q->lock);
        return RTOS_TIMEOUT;
    }
    
    if (q->count > 0) {
        memcpy(item, &q->buffer[q->tail * q->item_size], q->item_size);
        q->tail = (q->tail + 1) % q->max_items;
        q->count--;
        ret = RTOS_OK;
        pthread_cond_signal(&q->cond);
    }
    
    pthread_mutex_unlock(&q->lock);
    return ret;
#endif
}

void rtos_queue_delete(rtos_queue_t queue)
{
#ifdef USE_FREERTOS
    vQueueDelete((QueueHandle_t)queue);
#elif defined(USE_RTTHREAD)
    rt_mq_delete((rt_mq_t)queue);
#elif defined(USE_PTHREAD)
    rtos_queue_internal_t *q = (rtos_queue_internal_t *)queue;
    pthread_mutex_destroy(&q->lock);
    pthread_cond_destroy(&q->cond);
    free(q->buffer);
    free(q);
#endif
}

/* 软件定时器 */
rtos_timer_t rtos_timer_create(const char *name,
                              void (*timeout_func)(void *),
                              void *arg,
                              uint32_t timeout_ms,
                              bool auto_reload)
{
#ifdef USE_FREERTOS
    TimerHandle_t timer = xTimerCreate(name, 
                                     pdMS_TO_TICKS(timeout_ms), 
                                     auto_reload ? pdTRUE : pdFALSE, 
                                     arg, 
                                     (TimerCallbackFunction_t)timeout_func);
    return (rtos_timer_t)timer;
#elif defined(USE_RTTHREAD)
    rt_timer_t timer = rt_timer_create(name, 
                                      timeout_func, 
                                      arg, 
                                      rt_tick_from_millisecond(timeout_ms), 
                                      auto_reload ? RT_TIMER_FLAG_PERIODIC : RT_TIMER_FLAG_ONE_SHOT);
    return (rtos_timer_t)timer;
#elif defined(USE_PTHREAD)
    // pthread没有内置定时器，这里简化实现
    return NULL;
#endif
}

int rtos_timer_start(rtos_timer_t timer)
{
#ifdef USE_FREERTOS
    return (xTimerStart((TimerHandle_t)timer, 0) == pdPASS) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_RTTHREAD)
    return (rt_timer_start((rt_timer_t)timer) == RT_EOK) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_PTHREAD)
    return RTOS_ERROR; // 不支持
#endif
}

int rtos_timer_stop(rtos_timer_t timer)
{
#ifdef USE_FREERTOS
    return (xTimerStop((TimerHandle_t)timer, 0) == pdPASS) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_RTTHREAD)
    return (rt_timer_stop((rt_timer_t)timer) == RT_EOK) ? RTOS_OK : RTOS_ERROR;
#elif defined(USE_PTHREAD)
    return RTOS_ERROR; // 不支持
#endif
}

void rtos_timer_delete(rtos_timer_t timer)
{
#ifdef USE_FREERTOS
    xTimerDelete((TimerHandle_t)timer, 0);
#elif defined(USE_RTTHREAD)
    rt_timer_delete((rt_timer_t)timer);
#elif defined(USE_PTHREAD)
    // 无操作
#endif
}

/* 事件标志组 */
rtos_event_group_t rtos_event_group_create(void)
{
#ifdef USE_FREERTOS
    return (rtos_event_group_t)xEventGroupCreate();
#elif defined(USE_RTTHREAD)
    rt_event_t event = rt_event_create("event", RT_IPC_FLAG_FIFO);
    return (rtos_event_group_t)event;
#elif defined(USE_PTHREAD)
    // pthread没有内置事件标志组，这里简化实现
    return NULL;
#endif
}

uint32_t rtos_event_group_wait(rtos_event_group_t group,
                              uint32_t bits,
                              bool clear_on_exit,
                              bool wait_all,
                              uint32_t timeout_ms)
{
#ifdef USE_FREERTOS
    return xEventGroupWaitBits((EventGroupHandle_t)group,
                             bits,
                             clear_on_exit ? pdTRUE : pdFALSE,
                             wait_all ? pdTRUE : pdFALSE,
                             timeout_ms == RTOS_WAIT_FOREVER ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms));
#elif defined(USE_RTTHREAD)
    rt_uint32_t recved;
    rt_err_t result = rt_event_recv((rt_event_t)group,
                                   bits,
                                   wait_all ? RT_EVENT_FLAG_AND : RT_EVENT_FLAG_OR,
                                   timeout_ms == RTOS_WAIT_FOREVER ? RT_WAITING_FOREVER : rt_tick_from_millisecond(timeout_ms),
                                   &recved);
    if (result == RT_EOK && clear_on_exit) {
        rt_event_clear((rt_event_t)group, recved & bits);
    }
    return (result == RT_EOK) ? (recved & bits) : 0;
#elif defined(USE_PTHREAD)
    return 0; // 不支持
#endif
}

uint32_t rtos_event_group_set(rtos_event_group_t group, uint32_t bits)
{
#ifdef USE_FREERTOS
    return xEventGroupSetBits((EventGroupHandle_t)group, bits);
#elif defined(USE_RTTHREAD)
    rt_event_send((rt_event_t)group, bits);
    return bits;
#elif defined(USE_PTHREAD)
    return 0; // 不支持
#endif
}

uint32_t rtos_event_group_set_from_isr(rtos_event_group_t group, uint32_t bits)
{
#ifdef USE_FREERTOS
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    uint32_t result = xEventGroupSetBitsFromISR((EventGroupHandle_t)group, bits, &xHigherPriorityTaskWoken);
    if (xHigherPriorityTaskWoken) {
        portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
    }
    return result;
#elif defined(USE_RTTHREAD)
    if (rt_interrupt_get_nest() > 0) {
        rt_event_send((rt_event_t)group, bits);
        return bits;
    }
    return rtos_event_group_set(group, bits);
#elif defined(USE_PTHREAD)
    return 0; // 不支持
#endif
}

uint32_t rtos_event_group_clear(rtos_event_group_t group, uint32_t bits)
{
#ifdef USE_FREERTOS
    return xEventGroupClearBits((EventGroupHandle_t)group, bits);
#elif defined(USE_RTTHREAD)
    rt_event_clear((rt_event_t)group, bits);
    return bits;
#elif defined(USE_PTHREAD)
    return 0; // 不支持
#endif
}

void rtos_event_group_delete(rtos_event_group_t group)
{
#ifdef USE_FREERTOS
    vEventGroupDelete((EventGroupHandle_t)group);
#elif defined(USE_RTTHREAD)
    rt_event_delete((rt_event_t)group);
#elif defined(USE_PTHREAD)
    // 无操作
#endif
}

/* 系统控制 */
void rtos_start_scheduler(void)
{
#ifdef USE_FREERTOS
    vTaskStartScheduler();
#elif defined(USE_RTTHREAD)
    /* RT-Thread 会自动启动调度器 */
#elif defined(USE_PTHREAD)
    /* pthread不需要显式启动调度器 */
#endif
}

void rtos_yield(void)
{
#ifdef USE_FREERTOS
    taskYIELD();
#elif defined(USE_RTTHREAD)
    rt_schedule();
#elif defined(USE_PTHREAD)
    sched_yield();
#endif
}